package com.gd.coreservice.controller;



import com.gd.commonutils.Result;
import com.gd.coreservice.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
@CrossOrigin //解决跨域问题
public class OssController {
    @Autowired
    private OssService ossService;

    //上传头像的方法
    @PostMapping
    public Result uploadOssFile(
            MultipartFile file) { //MultipartFile file用来得到用户上传的文件
        //上传文件到oss,并得到文件的url
        String url = ossService.uploadFileAvatar(file);
        return Result.success(url);
    }
//仍然有问题  文件名中的filename中的2024/03/30会被解析成2024%03%30
    //下载下来的文件也打不开
    @GetMapping("/download/{filename}")
    public ResponseEntity<InputStreamResource> downloadFile(@PathVariable("filename") String filename) throws IOException {
        //处理文件名中的"/"
        filename = URLEncoder.encode(filename, "UTF-8");
        // 调用文件下载方法
        InputStream inputStream = ossService.downloadFile(filename);
        // 设置文件响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" + filename);
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(inputStream));
    }

}
